#ifndef MINIMAL_UNIFIED_MEMORY_MANAGER_H
#define MINIMAL_UNIFIED_MEMORY_MANAGER_H
#include "unified_memory_interfaces.h"
#include "fileidentitymanager.h"
#include "unifiedcachemanager.h"
#include <QFile>
#include <QDebug>
// 最小化统一内存管理器实现，提供基本的缓存加载功能
// 简化的统一缓存加载服务
class SimpleCacheLoadingService : public ICacheLoadingService {
public:
    LoadResult loadFromCache(const QString& fileIdentity, int pageIndex) override {
        LoadResult result;
        result.loadTime = QDateTime::currentDateTime();
        try {
            // 直接使用已验证工作的UnifiedCacheManager
            QImage image = UnifiedCacheManager::instance()->loadFromCache(fileIdentity, pageIndex);
            if (!image.isNull()) {
                result.image = image;
                result.success = true;
                result.memoryUsed = image.sizeInBytes();
                return result;
            }
            // 如果UnifiedCacheManager失败，回退到直接文件加载
            QString cacheKey = FileIdentityManager::getCacheKey(fileIdentity);
            QString cacheDir = UnifiedCacheManager::instance()->getCacheDirectory() + "/" + cacheKey;
            QString fileName = QString("page_%1.png").arg(pageIndex, 5, 10, QChar('0'));
            QString filePath = cacheDir + "/" + fileName;
            // 添加详细调试信息
            if (QFile::exists(filePath)) {
                QImage image(filePath);
                if (!image.isNull()) {
                    result.image = image;
                    result.success = true;
                    result.memoryUsed = image.sizeInBytes();
                } else {
                    result.errorMessage = "Image file corrupted";
                }
            } else {
                result.errorMessage = QString("Cache file not found: %1").arg(filePath);
                // 检查目录是否存在
                QDir dir(cacheDir);
                if (dir.exists()) {
                    QStringList allFiles = dir.entryList(QDir::Files);
                    if (allFiles.size() <= 10) {  // 只显示前10个文件
                    }
                } else {
                }
            }
        } catch (const std::exception& e) {
            result.errorMessage = QString("Exception: %1").arg(e.what());
        }
        return result;
    }
    bool isCacheAvailable(const QString& fileIdentity, int pageIndex) const override {
        QString cacheKey = FileIdentityManager::getCacheKey(fileIdentity);
        QString cacheDir = UnifiedCacheManager::instance()->getCacheDirectory() + "/" + cacheKey;
        QString fileName = QString("page_%1.png").arg(pageIndex, 5, 10, QChar('0'));
        QString filePath = cacheDir + "/" + fileName;
        return QFile::exists(filePath);
    }
    // 支持缩略图的加载
    LoadResult loadThumbnailFromCache(const QString& fileIdentity, int pageIndex) {
        LoadResult result;
        result.loadTime = QDateTime::currentDateTime();
        try {
            QString cacheKey = FileIdentityManager::getCacheKey(fileIdentity);
            QString cacheDir = UnifiedCacheManager::instance()->getCacheDirectory() + "/" + cacheKey;
            QString fileName = QString("thumb_%1.png").arg(pageIndex, 5, 10, QChar('0'));
            QString filePath = cacheDir + "/thumbnails/" + fileName;
            // 添加缩略图详细调试信息
            if (QFile::exists(filePath)) {
                QImage image(filePath);
                if (!image.isNull()) {
                    result.image = image;
                    result.success = true;
                    result.memoryUsed = image.sizeInBytes();
                } else {
                    result.errorMessage = "Thumbnail file corrupted";
                }
            } else {
                result.errorMessage = "Thumbnail cache file not found";
            }
        } catch (const std::exception& e) {
            result.errorMessage = QString("Thumbnail loading exception: %1").arg(e.what());
        }
        return result;
    }
};
// 简化的内存管理器（先让编译通过）
class MinimalUnifiedMemoryManager : public IUnifiedMemoryManager {
private:
    std::unique_ptr<ICacheLoadingService> m_cacheService;
    QString m_currentFileIdentity;
    QObject* m_mainWindow;  // 用于获取当前文件标识
public:
    explicit MinimalUnifiedMemoryManager(QObject* mainWindow = nullptr) 
        : m_mainWindow(mainWindow) {
        m_cacheService = std::make_unique<SimpleCacheLoadingService>();
    }
    void registerPool(ContentType type, size_t maxMemoryBytes) override {
        // 简化实现：暂时不做实际管理
    }
    QImage getImage(ContentType type, int index, int currentFocus = -1) override {
        Q_UNUSED(currentFocus);
        // 根据内容类型选择正确的加载方法
        QString fileIdentity = getCurrentFileIdentity();
        SimpleCacheLoadingService::LoadResult result;
        if (type == ContentType::THUMBNAIL) {
            // 加载缩略图
            auto* service = static_cast<SimpleCacheLoadingService*>(m_cacheService.get());
            result = service->loadThumbnailFromCache(fileIdentity, index);
        } else {
            // 加载主图或组合页
            result = m_cacheService->loadFromCache(fileIdentity, index);
        }
        return result.success ? result.image : QImage();
    }
    void setCurrentFocus(ContentType type, int focus) override {
        Q_UNUSED(type);
        Q_UNUSED(focus);
        // 简化实现：暂时不做处理
    }
    size_t getMemoryUsage(ContentType type) const override {
        Q_UNUSED(type);
        return 0;  // 简化实现
    }
    void setMemoryStrategy(ContentType type, std::unique_ptr<IMemoryStrategy> strategy) override {
        Q_UNUSED(type);
        Q_UNUSED(strategy);
        // 简化实现：暂时不做处理
    }
    // 设置当前文件标识（临时方法）
    void setCurrentFileIdentity(const QString& fileIdentity) {
        m_currentFileIdentity = fileIdentity;
    }
private:
    QString getCurrentFileIdentity() const {
        // 优先使用设置的文件标识，这是最可靠的
        if (!m_currentFileIdentity.isEmpty()) {
            return m_currentFileIdentity;
        }
        // 尝试从MainWindow获取当前文件标识
        if (m_mainWindow) {
            QVariant result;
            bool success = QMetaObject::invokeMethod(m_mainWindow, "currentFileIdentity", 
                                                   Qt::DirectConnection,
                                                   Q_RETURN_ARG(QVariant, result));
            if (success && result.isValid()) {
                QString fileIdentity = result.toString();
                if (!fileIdentity.isEmpty()) {
                    return fileIdentity;
                }
            }
        }
        // 最后回退到默认值
        return "default_file";
    }
};
#endif // MINIMAL_UNIFIED_MEMORY_MANAGER_H
